package com.samsungmobile.common_module.Parser;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.samsungmobile.common.Logger;
import com.samsungmobile.common_module.Bean.AlbumItem;
import com.samsungmobile.common_module.Bean.Item;
import com.samsungmobile.common_module.Bean.TrackItem;
import com.samsungmobile.common_module.Bean.Item.ItemType;

public class TrackResponseParser extends DefaultHandler implements ResponseParser {

	ResponseData responseData;
	InputStream responseContent;
	String responseContentString;
	
	public String getResponseContentString() {
		return responseContentString;
	}
	public void setResponseContentString(String responseContentString) {
		this.responseContentString = responseContentString;
	}


	private StringBuffer  sbfCharacter = new StringBuffer();
	private TrackItem curItem = null;
	
	private static final boolean isLogParsing = false;
	
	public void setResponseContent(InputStream responseContent) {
		this.responseContent = responseContent;
		
	}
	public InputStream getResponseContent() {
		return responseContent;
	}

	public ResponseData getResponseData() {
		return this.responseData;
	}
	
	public TrackResponseParser(){
	}

	public void process() throws ParserConfigurationException, SAXException {
		
		processStream();
	}
	
	public void processStream() throws ParserConfigurationException, SAXException {
		
//		Logger.LOG_NOHUP.debug("process()");
		SAXParserFactory factory   = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        
        responseData = new ResponseData(ItemType.track);

        // parse the response input stream
        try {
			saxParser.parse(this.responseContent,this);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void processString() throws ParserConfigurationException, SAXException {
		
//		Logger.LOG_NOHUP.debug("process()");
		SAXParserFactory factory   = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        
        responseData = new ResponseData(ItemType.track);

        // parse the response input stream
        try {
			saxParser.parse(new InputSource(new StringReader(this.responseContentString)),this);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}	
	
	/*
	* Called when the Parser starts parsing the Current XML File.
	*/
	public void startDocument () throws SAXException
	{
//		Logger.LOG_NOHUP.debug("startDocument()");
		responseData = new ResponseData(ItemType.track);
	}

	/*
	 * Called when the Parser Completes parsing the Current XML File.
	*/
	public void endDocument () throws SAXException
	{
//		Logger.LOG_NOHUP.debug("endDocument()");
	}

	/*
	 * Called when the starting of the Element is reached.
	*/
	public void startElement( String namespaceURI, String localName, 
	                            String qName, Attributes atts ) throws SAXException 

	{
		if(qName.equals("tracks")) {
			responseData.setItemList(new ArrayList<Item>());
		} else if(qName.equals("album")) {
			AlbumItem albumItem = new AlbumItem();
			this.curItem.setAlbum(albumItem);
		} else if(qName.equals("ResponseCode")) {
			try {
				if(atts != null && atts.getLength() > 0) {
					for(int i=0; i<atts.getLength(); i++) {
						if(atts.getQName(i) == "ErrCode") {
							responseData.setResponseCode(atts.getValue(i));
							Logger.LOG_NOHUP.debug("ResponseCode: "+atts.getValue(i));
						}
					}
				}
			} catch(Exception ex) {
				Logger.LOG_NOHUP.error(ex);
			}
		} else if(qName.equals("price")) {
			if(atts != null && atts.getLength() > 0) {
				for(int i=0; i<atts.getLength(); i++) {
					if(atts.getQName(i) == "country") {
						// set currency by country
						this.curItem.setCurrency(atts.getValue(i));
					}
				}
			}
		}
		
		sbfCharacter.setLength(0);
	}

	/*
	 * Called when the Ending of the current Element is reached. 
	*/
	public void endElement(String namespaceURI, String localName, String qName)
	{
		String val = sbfCharacter.toString();
		
		if(isLogParsing == true) {
			Logger.LOG_NOHUP.debug("endElement: "+qName+": "+val);
		}
		
		if(qName.equals("track")) {
			if(curItem != null){
				responseData.addItem(curItem);
			}
			curItem = new TrackItem();
		}
		else { 
			// response data
			if(qName.equals("message")) {
				responseData.setErrorMessage(val);
			} 
			
			try {
				// track data
				if(curItem == null) {
					curItem = new TrackItem();
				}
				
				if(qName.equals("contentId") || qName.equals("ContentId")) {
					curItem.setContentId(val);
				}else if(qName.equals("artist")) {
					curItem.setArtist(val);
				} else if(qName.equals("title")) {
					curItem.setTitle(val);
				} else if(qName.equals("price")) {
					try {
						curItem.setPrice(Double.valueOf(val));
					} catch(Exception ex) {
						Logger.LOG_NOHUP.error(ex);
					}
				} else if(qName.equals("date") || qName.equals("dateRelease")) {
					curItem.setReleaseDate(val);
				} else if(qName.equals("genre")) {
					curItem.setGenre(val);
				} else if(qName.equals("prelisten")) {
					curItem.setPrelisten(val);
				} else if(qName.equals("coverImage")) {
					curItem.setCoverImagePath(val);
				} else if(qName.equals("size")) {
					try {
						curItem.setSize(Integer.valueOf(val));
					} catch(Exception ex) {
						Logger.LOG_NOHUP.error(ex);
					}
				} else if(qName.equals("WAPpushURL")){
					curItem.setWapPushURL(val);
				}
				
				
				// Album data
				try {
					if(qName.equals("id")) {
						try {
							curItem.getAlbum().setUpc(val);
						} catch(Exception ex) {
							Logger.LOG_NOHUP.error(ex);
						}
					} else if (qName.equals("name")) {
						curItem.getAlbum().setTitle(val);
					} else if (qName.equals("url")) {
						curItem.getAlbum().setCoverImagePath(val);
					}
				} catch(Exception ex) {
					Logger.LOG_NOHUP.error(ex);
				}
				if(qName.equals("albumName")) {
					if(curItem.getAlbum() != null && curItem.getAlbum().getTitle() != null
							&& !curItem.getAlbum().getTitle().equals("")) {
						curItem.getAlbum().setTitle(val);
					}
				}
				
			} catch(Exception ex) {
				Logger.LOG_NOHUP.error(ex);
			}
		}
		
		sbfCharacter.setLength(0);
	}

	/*
	 * While Parsing the XML file, if extra characters like space or enter Character
	 * are encountered then this method is called.
	*/
	public void characters (char buf [], int offset, int length) throws SAXException
	{
		sbfCharacter.append(buf, offset, length);
	}


	public void processingInstruction (String target, String data) throws SAXException
	{

	}

}
